<template>
  <div class="Team-wrap">
      <el-button
        class="create-btn"
        type="success"
        size="small"
      @click="handleCreate">新增团队 +</el-button>
      <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
            label="团队id"
            width="100px"
            prop="id">
        </el-table-column>
        <el-table-column
            label="名称"
            width="100px"
            prop="name">
        </el-table-column>
        <el-table-column
            label="描述"
            width="250px"
            prop="desc">
        </el-table-column>
        <el-table-column
            label="创建时间"
            width="200px"
            prop="created_on"
            :formatter="formatterTime"
            >
        </el-table-column>
        <el-table-column
            label="当前人数"
            width="100px"
            prop="user_count">
        </el-table-column>
        <!-- <el-table-column
            label="停止招生"
            width="100px"
            prop="is_full">
        </el-table-column> -->
        <el-table-column
            align="right">
            <template #header>
                <el-input
                v-model="search"
                @blur="searchTeam"
                size="mini"
                placeholder="输入团队名称搜索"/>
            </template>
            <template #default="scope">
                <el-button
                size="mini"
                @click="handleMemberList(scope.$index, scope.row)">查看成员</el-button>
                <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
      class="page-wrap"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
    <el-dialog title="团队信息" v-model="dialogFormVisible">
        <el-form :model="form">
            <el-form-item label="名称" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth">
                <el-input v-model="form.desc" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmTeam">确 定</el-button>
            </span>
        </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import api from '../../../api/index'
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
  setup () {
    const router = useRouter()
    const dialogFormVisible = ref(false)
    const formLabelWidth = ref('120px')
    let status = '' // 区分是新增还是修改
    let TeamId = null // 修改数据时记录id

    

    // 获取资源列表
    const tableData = ref([])
    async function getList (params) {
      const res = await api.getMyTeams({created_by: localStorage.getItem('user_id'),...params})
      if (res.data.code === 200) {
        tableData.value = res.data.data.list
        totalCount.value = res.data.data.pager.total_rows
      } else {
        ElMessage.error('获取资源列表失败：' + res.data.msg)
      }
    }
    getList()

    const form = ref({
      name: '',
      desc: '',
    })

    // 提交资源信息
    async function confirmTeam () {
      // 验证信息是否齐全
      if (!(form.value.name)) {
        ElMessage.error('表单信息不全')
        return
      }
      switch (status) {
        case 'create':
          createTeam(form.value)
          break
        case 'edit':
          updateTeam(TeamId, form.value)
          break
      }
    }

    // 新增团队
    async function handleCreate () {
      form.value = {
        name: '',
        desc: '',
      }
      dialogFormVisible.value = true
      status = 'create'
    }
    // 添加团队
    async function createTeam (params) {
      const res = await api.createTeam(params)
      if (res.data.code === 200) {
        getList()
        ElMessage.success({
          message: '添加成功',
          type: 'success'
        })
        dialogFormVisible.value = false
      } else {
        ElMessage.error('添加失败：' + res.data.msg)
      }
    }

    // 编辑团队
    async function handleEdit (index, row) {
      console.log(index, row)
      dialogFormVisible.value = true
      status = 'edit'
      form.value.name = row.name
      form.value.desc = row.desc
      TeamId = row.id
    }
    // 修改团队信息
    async function updateTeam (id, params) {
      const res = await api.updateTeam(id, params)
      if (res.data.code === 200) {
        ElMessage.success({
          message: '修改成功',
          type: 'success'
        })
        getList()
        dialogFormVisible.value = false
      } else {
        ElMessage.error('修改失败：' + res.data.msg)
      }
    }

    // 删除用户
    async function handleDelete (index, row) {
      ElMessageBox.confirm('此操作将永久删除该资源, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delTeam(row.id)
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
    // 删除团队
    async function delTeam (id) {
      const res = await api.delTeam(id)
      if (res.data.code === 200) {
        getList()
        ElMessage.success({
          type: 'success',
          message: '删除成功!'
        })
      } else {
        ElMessage.error('删除失败：' + res.data.msg)
      }
    }

    // 搜索资源
    const search = ref('')
    async function searchTeam () {
      currentPage.value = 1
      pageSize.value = 10
      if (search.value === '') {
        getList({ page: currentPage.value, page_size: pageSize.value })
        return
      }
      currentPage.val = 1
      const res = await api.findTeamByName({ name: search.value })
      if (res.data.code === 200) {
        tableData.value = res.data.data.list
        ElMessage.success({
          message: '搜索成功',
          type: 'success'
        })
      } else {
        ElMessage.error('修改失败：' + res.data.msg)
      }
    }

    // 跳转成员列表
    function handleMemberList(index, row) {
      router.push({name:'TeamMembers', params: row})
    }

    // 分页相关
    const currentPage = ref(1)
    const totalCount = ref(0)
    const pageSize = ref(10)
    function handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      getList({ pageindex: currentPage.value, pagesize: val })
    }
    function handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      getList({ page: val, page_size: pageSize.value })
    }
    // 超过一页就隐藏分页插件
    const hideOnSinglePage = computed(() => {
      return totalCount.value <= 10
    })
      // 格式化时间
    function formatterTime(row, column, cellValue) {
      return new Date(cellValue).toLocaleString()
    }

    return {
      tableData,
      search,
      handleEdit,
      handleDelete,
      handleCreate,
      dialogFormVisible,
      formLabelWidth,
      form,
      confirmTeam,
      searchTeam,
      currentPage,
      totalCount,
      handleSizeChange,
      handleCurrentChange,
      pageSize,
      hideOnSinglePage,
      handleMemberList,
      formatterTime
    }
  }
}
</script>

<style lang="scss" scoped>
    .Team-wrap{
        width: 100%;
        min-width: 500px;
        .create-btn{
            margin-bottom: 10px;
            display: flex;
            justify-content: flex-end;
        }
        .upload-demo{
            display: flex;
            align-items: center;
            justify-content: start;
        }
        .page-wrap{
            margin-top: 10px;
        }
    }
</style>
